package com.oasystem.web.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.oasystem.domain.Operator;
import com.oasystem.service.OperatorService;

@Controller
public class LoginController {
	private Logger log = Logger.getLogger(this.getClass());
	@Resource(name="operatorService")
	private OperatorService operatorService;
	
	@RequestMapping(value = "/loginPage")
	public String loginPage() {
		return "login";
	}
	
	@RequestMapping(value = "/login")
	public @ResponseBody ModelMap login(String loginName,String password,HttpSession session) {
		log.info("do Login, name="+loginName+" password="+password);
		ModelMap model = new ModelMap("data");
		
		Operator operator = new Operator(loginName,password);
		if(operatorService.isLegal(operator)){
			log.info("login success");
			model.addAttribute("operator", operator);
			session.setAttribute("OPERATOR", operator);
			model.addAttribute("success", "success");
		}else{
			log.info("login failure");
			model.addAttribute("error", "error");
		}
		return model;
	}
	
	@RequestMapping(value = "/logout")
	public @ResponseBody ModelMap logout(HttpSession session) {
		ModelMap model = new ModelMap("data");
		session.invalidate();
		return model;
	}

	@RequestMapping(value = "/urlGuide")
	public @ResponseBody ModelMap urlGuide(HttpSession session) {
		ModelMap model = new ModelMap("data");
		Operator op = (Operator) session.getAttribute("OPERATOR");
		String uri="login";
		if(op.isAllowAddMember()){
			uri="/MainMenu/members/addMemberPage";
		}else if(op.isAllowSearchMember()){
			uri="/MainMenu/members/searchResultPage";
		}else if(op.isAllowSummaryMember()){
			uri="/MainMenu/members/summaryPage";
		}else if(op.isAllowAddProfit()){
			uri="/MainMenu/profit/addPage";
		}else if(op.isAllowSearchProfit()){
			uri="/MainMenu/profit/searchPage";
		}else if(op.isAllowSummaryProfit()){
			uri="/MainMenu/profit/summaryPage";
		}else if(op.isAllowManageOperator()){
			uri="/MainMenu/configuration/operatorPage";
		}else if(op.isAllowManageGoods()){
			uri="/MainMenu/configuration/goodsPage";
		}else if(op.isAllowManageDepartment()){
			uri="/MainMenu/configuration/departmentPage";
		}else if(op.isAllowManageDataSafe()){
			uri="/MainMenu/configuration/dataSafePage";
		}
		model.addAttribute("uri", uri);
		return model;
	}
}
